﻿using log4net;
using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace ScreenshotViewer
{
    public partial class Viewer : Form
    {
        private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        int _currentImageNumber = 0;
        string _imageFileName;
        System.Threading.Timer _timer;
        delegate void SetImage();
        SetImage InvokeSetImage;

        public Viewer()
        {
            InitializeComponent();
        }

        private void Viewer_Load(object sender, EventArgs e)
        {
            // this.TopMost = true;
            this.Icon = Properties.Resources.Icon1;
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            this.pictureBox1.Top = 0;
            this.pictureBox1.Left = 0;
            this.pictureBox1.Height = this.Size.Height;
            this.pictureBox1.Width = this.Size.Width;
            this.pictureBox1.Image = GetRandomImage();
            _timer = new System.Threading.Timer(NextImage, this, (int)TimeSpan.FromSeconds(10).TotalMilliseconds, (int)TimeSpan.FromSeconds(10).TotalMilliseconds);
            InvokeSetImage = delegate { this.pictureBox1.Image = Image.FromFile(_imageFileName); };
            Cursor.Hide();
        }

        private void NextImage(object state)
        {
            Log.Debug("Enter");

            var form = state as Viewer;
            if (form == null)
            {
                Log.Error($"That's weird, form is null!");
                return;
            }

            var files = GetImageFiles();
            if (files.Count() > 0)
            {
                if (form._currentImageNumber < files.Count() - 1)
                {
                    form._currentImageNumber++;
                }
                else
                {
                    form._currentImageNumber = 0;
                }

                form._imageFileName = files[form._currentImageNumber];
                try
                {
                    form.BeginInvoke(InvokeSetImage);
                }
                catch (Exception ex)
                {
                    Log.Error($"Could not call InvokeSetImage delegate", ex);
                }
            }
        }

        private Image GetRandomImage()
        {
            string[] files = GetImageFiles();
            if (files.Count() > 0)
            {
                _currentImageNumber = new Random().Next(0, files.Length - 1);
                return Image.FromFile(files[_currentImageNumber]);
            }

            return Image.FromFile("default.jpg");
        }

        private static string[] GetImageFiles()
        {
            var pictureFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            var files = Directory.GetFiles(pictureFolder)
                .Where(p => IsImageFile(p) && new FileInfo(p).Length > 100 * 1028)
                .ToArray();
            Log.Debug($"[{files.Count()}] images found in folder [{pictureFolder}]");
            return files;
        }

        private static bool IsImageFile(string fileName)
        {
            //var re = new Regex(@"\.bmp|\.jpg|\.png", RegexOptions.IgnoreCase);
            //return re.IsMatch(fileName);

            return true;
        }

        private void Viewer_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                if (this.WindowState == FormWindowState.Normal)
                {
                    this.FormBorderStyle = FormBorderStyle.None;
                    this.WindowState = FormWindowState.Maximized;
                    this.pictureBox1.Height = this.Size.Height;
                    this.pictureBox1.Width = this.Size.Width;
                    Cursor.Hide();
                }
                else
                {
                    this.FormBorderStyle = FormBorderStyle.SizableToolWindow;
                    this.WindowState = FormWindowState.Normal;
                    this.pictureBox1.Height = this.Size.Height;
                    this.pictureBox1.Width = this.Size.Width;
                    Cursor.Show();
                }
            }
        }

        private void Viewer_ResizeEnd(object sender, EventArgs e)
        {
            this.pictureBox1.Height = this.Size.Height;
            this.pictureBox1.Width = this.Size.Width;
        }

        private void Viewer_FormClosed(object sender, FormClosedEventArgs e)
        {
            _timer = null;
            Environment.Exit(0);
        }
    }
}
